import SwiftUI
import KSPlayer
import Combine

struct KSVideoPlayerWrapper: View {
    let videoURL: String
    let videoType: Int
    let videoId: String?
    let shouldAutoPlay: Bool
    let isMuted: Bool
    @State private var playerCoordinator = KSVideoPlayer.Coordinator()
    @State private var options = KSOptions()
    @State private var isPlayerReady = false
    @State private var errorMessage: String?
    @State private var bufferingProgress = 0
    @State private var bufferedCount = 0
    @State private var consumeTime: TimeInterval = 0
    @ObservedObject private var playbackManager = VideoPlaybackManager.shared
    @State private var cancellables = Set<AnyCancellable>()
    @State private var isPreloading = false
    
    init(videoURL: String, videoType: Int = 0, videoId: String? = nil, shouldAutoPlay: Bool = true, isMuted: Bool = false) {
        self.videoURL = videoURL
        self.videoType = videoType
        self.videoId = videoId
        self.shouldAutoPlay = shouldAutoPlay
        self.isMuted = isMuted
    }
    
    var body: some View {
        // 直接使用原始URL，不使用缓存
        let actualVideoURL = videoURL
        
        if let url = URL(string: actualVideoURL) {
            ZStack {
                KSVideoPlayer(
                    coordinator: playerCoordinator,
                    url: url,
                    options: options
                )
                .onStateChanged { layer, state in
                    handleStateChange(layer: layer, state: state)
                }
                .onBufferChanged { bufferedCount, consumeTime in
                    self.bufferedCount = bufferedCount
                    self.consumeTime = consumeTime
                    
                    // 修复缓冲进度计算，避免除零错误
                    if consumeTime > 0, options.preferredForwardBufferDuration > 0 {
                        self.bufferingProgress = min(100, Int((consumeTime / options.preferredForwardBufferDuration) * 100))
                    } else {
                        self.bufferingProgress = 0
                    }
                }
                .onPlay { currentTime, totalTime in
                    // 当开始播放时，手动更新缓冲信息
                    if let playerLayer = playerCoordinator.playerLayer {
                        let bufferedCount = playerLayer.bufferingProgress
                        let consumeTime = totalTime > 0 ? currentTime : 0
                        
                        self.bufferedCount = bufferedCount
                        self.consumeTime = consumeTime
                        
                        if consumeTime > 0, options.preferredForwardBufferDuration > 0 {
                            self.bufferingProgress = min(100, Int((consumeTime / options.preferredForwardBufferDuration) * 100))
                        }
                    }
                }
                .onFinish { layer, error in
                    // 播放完成或出错时的处理
                    if let error = error {
                        self.errorMessage = error.localizedDescription
                    }
                }
                .onAppear {
                    // 添加调试日志
                    print("🎬 播放器初始化:")
                    print("   - 视频ID: \(videoId ?? "nil")")
                    print("   - 原始URL: \(videoURL)")
                    print("   - 实际URL: \(actualVideoURL)")
                    print("   - 使用缓存: 否 (已禁用缓存功能)")
                    
                    setupPlayer()
                    
                    // 缓存功能已禁用
                    
                    // 监听播放管理器状态变化
                    playbackManager.$currentPlayingVideoId
                        .sink { currentVideoId in
                            self.handlePlaybackManagerStateChange(currentVideoId: currentVideoId)
                        }
                        .store(in: &cancellables)
                    
                    // 监听预加载状态变化
                    playbackManager.$preloadVideoId
                        .sink { preloadVideoId in
                            self.handlePreloadStateChange(preloadVideoId: preloadVideoId)
                        }
                        .store(in: &cancellables)
                    
                    // 监听缓存完成通知
                    NotificationCenter.default.publisher(for: NSNotification.Name("VideoCacheCompleted"))
                        .sink { notification in
                            if let userInfo = notification.userInfo,
                               let cachedVideoId = userInfo["videoId"] as? String,
                               cachedVideoId == self.videoId {
                                self.handleCacheCompleted()
                            }
                        }
                        .store(in: &cancellables)
                }
                .onDisappear {
                    // 停止播放并释放资源
                    playerCoordinator.playerLayer?.pause()
                    playerCoordinator.playerLayer?.stop()
                    
                    // 清理订阅
                    cancellables.removeAll()
                    
       
                }
                
                // 简化的加载指示器（仅显示加载动画，不显示调试信息）
                if !isPlayerReady {
                    VStack(spacing: 12) {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle(tint: .white))
                            .scaleEffect(1.2)
                        
                        // 缓存功能已禁用
                        
                        if let errorMessage = errorMessage {
                            Text("播放失败: \(errorMessage)")
                                .foregroundColor(.red)
                                .font(.caption)
                                .padding(.top, 4)
                                .multilineTextAlignment(.center)
                        }
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background(Color.black.opacity(0.3))
                }
            }
        } else {
            // URL 无效时的占位视图
            VStack {
                Image(systemName: "exclamationmark.triangle")
                    .font(.largeTitle)
                    .foregroundColor(.red)
                Text("无效的视频链接")
                    .font(.caption)
                    .foregroundColor(.secondary)
                Text("URL: \(videoURL)")
                    .font(.caption2)
                    .foregroundColor(.secondary)
                    .padding(.top, 4)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.black)
        }
    }
    
    private func handleStateChange(layer: KSPlayerLayer, state: KSPlayerState) {
        DispatchQueue.main.async {
            print("🎬 播放状态变化: \(state)")
            
            switch state {
            case .readyToPlay:
                self.isPlayerReady = true
                self.errorMessage = nil
                print("✅ 播放器准备就绪")
                
                // 检查是否应该播放此视频
                if self.shouldAutoPlay && self.shouldPlayCurrentVideo() {
                    print("▶️ 开始自动播放")
                    layer.play()
                } else {
                    print("ℹ️ 播放器准备就绪但不需要播放: shouldAutoPlay=\(self.shouldAutoPlay), shouldPlay=\(self.shouldPlayCurrentVideo())")
                }
            case .preparing:
                self.isPlayerReady = false
                self.errorMessage = nil
                print("🔄 播放器准备中...")
            case .bufferFinished:
                self.isPlayerReady = true
                print("✅ 缓冲完成")
                
                // 缓冲完成时检查是否应该播放
                if self.shouldAutoPlay && self.shouldPlayCurrentVideo() {
                    print("▶️ 缓冲完成后开始播放")
                    layer.play()
                } else {
                    print("ℹ️ 缓冲完成但不需要播放: shouldAutoPlay=\(self.shouldAutoPlay), shouldPlay=\(self.shouldPlayCurrentVideo())")
                }
            case .buffering:
                self.isPlayerReady = false
                print("⏳ 正在缓冲...")
            case .playedToTheEnd:
                print("🏁 播放完成")
                break
            case .error:
                self.errorMessage = "播放失败"
                self.isPlayerReady = false
                print("❌ 播放出错")
            case .paused:
                print("⏸️ 播放暂停")
                break
            case .initialized:
                print("🚀 播放器初始化完成")
                break
            @unknown default:
                print("❓ 未知播放状态: \(state)")
                break
            }
        }
    }
    
    // 检查当前视频是否应该播放
    private func shouldPlayCurrentVideo() -> Bool {
        guard let videoId = videoId else { return false }
        return playbackManager.shouldPlay(videoId: videoId)
    }
    
    // 处理播放管理器状态变化
    private func handlePlaybackManagerStateChange(currentVideoId: String?) {
        guard let videoId = videoId else { return }
        
        print("🔄 播放管理器状态变化: 当前视频ID=\(currentVideoId ?? "nil"), 本视频ID=\(videoId)")
        
        if currentVideoId == videoId {
            // 当前视频应该播放
            print("▶️ 应该播放视频: \(videoId)")
            if let playerLayer = playerCoordinator.playerLayer {
                print("🎮 播放器状态: \(playerLayer.state)")
                DispatchQueue.main.async {
                    playerLayer.play()
                    print("▶️ 调用播放: \(videoId)")
                }
            }
        } else {
            // 当前视频应该暂停
            print("⏸️ 应该暂停视频: \(videoId)")
            if let playerLayer = playerCoordinator.playerLayer, playerLayer.state != .paused {
                DispatchQueue.main.async {
                    playerLayer.pause()
                    print("⏸️ 调用暂停: \(videoId)")
                }
            }
        }
    }
    
    // 处理预加载状态变化
    private func handlePreloadStateChange(preloadVideoId: String?) {
        guard let videoId = videoId else { return }
        
        if preloadVideoId == videoId {
            // 开始预加载
            isPreloading = true
            if let playerLayer = playerCoordinator.playerLayer {
                // 预加载时不播放，只准备
                DispatchQueue.main.async {
                    playerLayer.prepareToPlay()
                }
            }
        } else {
            // 停止预加载
            isPreloading = false
        }
    }
    
    // 处理缓存完成
    private func handleCacheCompleted() {
        guard let videoId = videoId else { return }
        
        print("🎉 缓存完成，检查是否需要播放: \(videoId)")
        
        // 检查是否应该播放此视频
        if playbackManager.shouldPlay(videoId: videoId) {
            print("▶️ 缓存完成，开始播放: \(videoId)")
            
            // 延迟一点时间确保播放器完全准备好
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                if let playerLayer = self.playerCoordinator.playerLayer {
                    print("🎮 缓存完成后播放，播放器状态: \(playerLayer.state)")
                    playerLayer.play()
                } else {
                    print("⚠️ 缓存完成但播放器未就绪，延迟播放")
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        if let playerLayer = self.playerCoordinator.playerLayer {
                            playerLayer.play()
                            print("▶️ 延迟播放成功: \(videoId)")
                        }
                    }
                }
            }
        } else {
            print("ℹ️ 缓存完成但不需要播放: \(videoId)")
        }
    }
    
    private func setupPlayer() {
        // 配置播放器选项 - 针对 m3u8 优化
        options.isSecondOpen = true  // 开启秒开
        options.isAccurateSeek = true  // 精确 seek
        // 根据视频ID判断是否为DetailView，DetailView启用循环播放
        let isDetailView = Int(videoId ?? "0") ?? 0 < 20000
        options.isLoopPlay = isDetailView  // DetailView循环播放，FeedView不循环
        options.isSeekedAutoPlay = true  // seek 后自动播放
        
        // 设置使用 MEPlayer 作为主要播放器（对 m3u8 支持更好）
        KSOptions.secondPlayerType = KSMEPlayer.self
        
        // m3u8 专用优化配置 - 平衡性能和稳定性
        if videoURL.hasSuffix(".m3u8") {
            
            // 秒开配置
            options.isSecondOpen = true
            options.codecLowDelay = true  // 低延迟解码
            
            // HLS 专用优化配置 - 平衡性能和稳定性
            options.formatContextOptions["reconnect"] = 1
            options.formatContextOptions["reconnect_streamed"] = 1
            options.formatContextOptions["scan_all_pmts"] = 1
            options.formatContextOptions["fflags"] = "fastseek"  // 只保留快速seek
            options.formatContextOptions["flags"] = "low_delay"  // 低延迟标志
            
            // 网络优化 - 减少超时时间，降低内存占用
            options.formatContextOptions["timeout"] = 5000000  // 5秒超时
            options.formatContextOptions["rw_timeout"] = 5000000
            options.formatContextOptions["analyzeduration"] = 2000000  // 2秒分析时长
            options.formatContextOptions["probesize"] = 2000000  // 2MB探测大小
            
            // 设置 User-Agent
            options.userAgent = "KSPlayer/1.0 (iOS; HLS; Optimized)"
            
            // 启用硬件解码和异步解压缩
            options.hardwareDecode = true
            options.asynchronousDecompression = true
            
            // 减少重试次数，避免长时间等待和内存占用
            options.formatContextOptions["max_retry_count"] = 1  // 最大重试次数
            options.formatContextOptions["retry_interval"] = 500000  // 重试间隔（微秒）
            
            // 允许 HTTP/HTTPS 协议访问
            options.formatContextOptions["protocol_whitelist"] = "file,http,https,crypto,data"
            
            
            // 禁用自动选择内嵌字幕，减少延迟
            options.autoSelectEmbedSubtitle = false
        } else {
        }
        
        // 设置视频内容模式
        playerCoordinator.isScaleAspectFill = videoType == 1
        
        // 设置音量和静音状态
        playerCoordinator.playbackVolume = 1.0
        playerCoordinator.isMuted = isMuted
        
        // 启用播放器自带控件
        KSOptions.isAutoPlay = shouldAutoPlay
    }
}

// 预览
#Preview {
    KSVideoPlayerWrapper(
        videoURL: "http://www.cosck.com:444/video/video2.library/images/M64FDMU8YJXOL.info/hls/13203.m3u8",
        videoType: 1
    )
    .frame(maxWidth: .infinity,maxHeight: 300)
}
